<!-- 编辑弹窗 -->
<template>
  <el-dialog :destroy-on-close="true" :lock-scroll="false" :title="isUpdate?'编辑联系人':'新建联系人'"
             append-to-body
             :visible="visible" custom-class="ele-dialog-form" width="600px" @update:visible="updateVisible">
    <el-form ref="form" :model="form" :rules="rules" label-width="92px" @keyup.enter.native="save"
             @submit.native.prevent>

      <el-form-item label="客户" prop="customer_name">
        <el-autocomplete v-model="form.customer_name" :fetch-suggestions="querySearchAsync" class="w-full" disabled
                         placeholder="搜索客户" value-key="name" @select="handleSelect">
          <template slot-scope="{ item }">
            <div style="margin-bottom: 10px;">
              <div>客户名称：{{ item.name }}</div>
              <div>客户编号：{{ item.customer_number }}</div>
            </div>
          </template>
        </el-autocomplete>
      </el-form-item>
      <el-form-item label="姓名:" prop="name">
        <el-input v-model="form.name" placeholder="请输入姓名"/>
      </el-form-item>

      <el-form-item label="性别:" prop="gender">
        <el-select v-model="form.gender" class="w-full" placeholder="请选择">
          <el-option label="男" value="male"/>
          <el-option label="女" value="female"/>
          <el-option label="保密" value="secret"/>
        </el-select>
      </el-form-item>

      <el-form-item label="联系电话" prop="phone">
        <el-input v-model="form.phone" placeholder="请输入联系电话"/>
      </el-form-item>

      <el-form-item label="办公电话" >
        <el-input v-model="form.office_phone" placeholder="请输入办公电话"/>
      </el-form-item>



      <el-form-item label="电子邮箱" prop="email" >
        <el-input v-model="form.email" placeholder="请输入电子邮箱"/>
      </el-form-item>

      <el-form-item label="出生日期" >
        <el-date-picker v-model="form.birthday" class="c-picker" placeholder="选择出生日期" type="date"
                        value-format="yyyy-MM-dd"/>
      </el-form-item>

      <el-form-item label="职务" >
        <el-input v-model="form.duty" placeholder="请输入职务"/>
      </el-form-item>

      <el-form-item label="项目角色" >
        <el-input v-model="form.project_role" placeholder="请输入项目角色"/>
      </el-form-item>

      <el-form-item label="所属区域:" >
        <div class="area">
          <City @areaChange="areaChange" :ids="cityName" ref="city"/>
        </div>
      </el-form-item>
      <el-form-item label="详细地址" >
        <el-input v-model="form.address" placeholder="请输入详细地址"/>
      </el-form-item>

      <el-form-item label="默认联系人" >
        <el-checkbox v-model="form.is_default" checked/>
      </el-form-item>
    </el-form>
    <div slot="footer">
      <el-button @click="updateVisible(false)">取消</el-button>
      <el-button :loading="loading" type="primary" @click="save">保存</el-button>
    </div>
  </el-dialog>
</template>

<script>
import City from '@/components/city'

export default {
  name: 'AddConcat',
  components: {City},
  props: {
    // 弹窗是否打开
    visible: Boolean,
    // 修改回显的数据
    data: Object,
    // 全部城市数据
    deptList: Array
  },
  data() {
    const validatePhone = (rule, value, callback) => {
      if (!value) {
        callback(new Error("请输入电话"))
      } else if (!this.phoneReg.test(value)) {
        callback(new Error("电话格式不正确"))
      } else {
        callback()
      }
    }
    const validateArea = (rule, value, callback) => {
      if (this.city.length === 0) {
        callback(new Error("请输入电话"))
      } else {
        callback()
      }
    }

    const validateCustomer_name = (rule, value, callback) => {
      if (this.form.customer_name==='') {
        callback(new Error("请选择客户"))
      } else {
        callback()
      }
    }
    return {
      //省市区
      cityName: '',
      phoneReg: /(1[3-9]\d{9}$)/,
      // 选中的省市区
      city: [],
      // 选中的省市
      provinceCity: [],
      // 选中的省
      province: [],
      //表单数组配置项
      dataList: [],
      // 表单数据
      form: this.initFormData(this.data),
      // 提交状态
      loading: false,
      // 是否是修改
      isUpdate: false,
      // 回顯客戶單位名稱
      customer_name: "",
      //表单验证规则
      rules: {
        area: [
          {required: true, trigger: "change", validator: validateArea}
        ],
        customer_name: [
          {required: true, validator: validateCustomer_name, trigger: 'blur'}
        ],
        name: [
          {required: true, message: '请输入姓名', trigger: 'blur'}
        ],
        gender: [
          {required: true, message: '请选择性别', trigger: 'blur'}
        ],
        phone: [
          {required: true, trigger: "blur", validator: validatePhone}
        ],
      }
    };
  },
  watch: {
    immediate: true,
    data() {
      this.isUpdate = !!(this.data && this.data.id);
      this.form = this.initFormData(this.data);
      this.isUpdate ? this.city = [(this.data.province_id).toString(), (this.data.city_id).toString(), (this.data.county_id).toString()] : this.city = []
      this.isUpdate ? this.customer_name = this.data.customer_name : this.customer_name = ""
      if (this.isUpdate && this.data) {
        this.cityName=this.data.province_name+'/'+this.data.city_name+'/'+this.data.county_name
        //刷新数据
        this.$nextTick(()=>{
          this.$refs.city.addressIds = this.data.province_name?this.data.province_name + '/' + this.data.city_name + '/' + this.data.county_name:''
        })
      }
      this.$forceUpdate()

      if (!this.isUpdate) {
        this.$refs.city.addressIds = ''
      }
    }
  },
  created() {
  },
  methods: {
    areaChange(val) {
      this.city = val
    },
    querySearchAsync(query, cb) {
      this.$http.get("customers", {
        params: {
          keyword: query,
          page: 1,
          limit: 10
        }
      }).then((res) => {
        cb(res.data.data);
      });
    },
    handleSelect(item) {
      this.form.customer_name = item.name
      this.form.customer_id = item.id;
    },
    /* 保存编辑 */
    save() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          this.form = Object.assign({}, this.form, {
            province_id: this.city[0],
            city_id: this.city[1],
            county_id: this.city[2]
          });
          if (this.isUpdate) {
            this.loading = true;
            this.$http.put('customer_users/' + this.data.id, Object.assign({}, this.form,)).then(res => {
              this.loading = false;
              if (res.data.code === 0) {
                this.$message.success(res.data.msg);
                this.updateVisible(false);
                this.$emit('done');
              } else {
                this.$message.error(res.data.msg);
              }
            }).catch(e => {
              this.loading = false;
              this.$message.error(e.message);
            });
          } else {
            this.form = Object.assign({}, this.form, {
              province_id: this.city[0],
              city_id: this.city[1],
              county_id: this.city[2]
            });
            this.loading = true;
            this.$http.post('customer_users', Object.assign({}, this.form)).then(res => {
              this.loading = false;
              if (res.data.code === 0) {
                this.$message.success(res.data.msg);
                this.updateVisible(false);
                this.$emit('done',res.data.data);
              } else {
                this.$message.error(res.data.msg);
              }
            }).catch(e => {
              this.loading = false;
              this.$message.error(e.message);
            });
          }
        } else {
          return false;
        }
      });
    },
    /* 更新visible */
    updateVisible(value) {
      if (!this.isUpdate) {
        this.form = {};
        this.customer_name = '';
      }
      this.$emit('update:visible', value);
    },
    /* 初始化form数据 */
    initFormData(data) {
      // 初始化默认值
      let form = {level: 1};
      if (data) {
        Object.assign(form, data);
      }
      return form;
    }
  }
}
</script>

<style scoped>
.area /deep/.el-cascader{
  width: 100%;
}

.el-select {
  width: 100%;
}

.el-autocomplete {
  width: 100%;
}

.el-input {
  width: 100% !important;
}
</style>
